package com.fitness.fitness.service.impl.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.fitness.fitness.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.Date;

@Slf4j
@Service
public class UploadFileServiceImpl {

    @Resource
    private Environment environment;

    //项目工作目录下新建一个files目录存文件
    public static final String DEFAULT_UPLOAD_FOLDER = FileUtil.getParent(System.getProperty("user.dir"),1)
            + FileUtil.FILE_SEPARATOR + "files" + FileUtil.FILE_SEPARATOR + "admin" + FileUtil.FILE_SEPARATOR;

    public static final String DEFAULT_RETURN_URL = "/file/";

    public UploadFileServiceImpl() {
        if(!FileUtil.exist(DEFAULT_UPLOAD_FOLDER)){
            FileUtil.mkdir(DEFAULT_UPLOAD_FOLDER);
        }
    }

    public String uploadFile(InputStream inputStream, String fileName) {
        File file = FileUtil.writeFromStream(inputStream,DEFAULT_UPLOAD_FOLDER + IdUtil.simpleUUID() + "." +FileUtil.getSuffix(fileName));
        return getHostPortAppInfo() + DEFAULT_RETURN_URL + file.getName();
    }


    private String getHostPortAppInfo() {
        try{
            String port = environment.getProperty("server.port");
            String ip = InetAddress.getLocalHost().getHostAddress();
            String contextPath = environment.getProperty("server.servlet.context-path");
            if (StrUtil.isBlank(contextPath)) {
                contextPath = "";
            }
            return "http://" + ip + ":" + port + contextPath;
        } catch (Exception e) {
            throw new BizException("获取主机信息失败!");
        }
    }

    private String mkDirByDay(){
        Date now = new Date();
        int year = DateUtil.year(now);
        //月份从0开始
        int month = DateUtil.month(now) + 1;
        int day = DateUtil.dayOfMonth(now);

        return null;
    }

    public static void main(String[] args) {
        File f = new File("/home/tzg157/tmp/paobuji.jpg");
        System.out.println(f.getName());
    }
}
